﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.Unity;

namespace ilgolosone.DependencyResolver.Unity.UnitTests
{
    /// <summary>
    /// Extension per Unity che permette di controllare quali tipi sono registrati nel container.
    /// </summary>
    internal sealed class RegisteredTypesExtension : UnityContainerExtension
    {
        private readonly List<RegisterEventArgs> _registrations = new List<RegisterEventArgs>();

        protected override void Initialize()
        {
            Context.Registering += Context_Registering;
        }

        void Context_Registering(object sender, RegisterEventArgs e)
        {
            _registrations.Add(e);
        }

        public bool HasImplementationsFor<TSource>()
        {
            return _registrations.FirstOrDefault(
               e => e.TypeFrom == typeof(TSource)) != null;
        }

        public bool HasImplementationsFor(Type sourceType)
        {
            return _registrations.FirstOrDefault(
               e => e.TypeFrom == sourceType) != null;
        }

        public bool IsTypeRegistered<TFrom, TTo>()
        {
            return _registrations.FirstOrDefault(
                e => e.TypeFrom == typeof(TFrom) && 
                       e.TypeTo == typeof(TTo)) != null;
        }

        public bool IsTypeRegisteredAsSingleton<TFrom, TTo>()
        {
            return _registrations.FirstOrDefault(
                e => e.TypeFrom == typeof(TFrom) && 
                       e.TypeTo == typeof(TTo) && 
                       typeof(ContainerControlledLifetimeManager).IsInstanceOfType(e.LifetimeManager)) != null;
        }

        public List<RegisterEventArgs> Registrations
        {
            get { return _registrations; }
        }
    }
}
